// https://leetcode.cn/problems/frequency-of-the-most-frequent-element/submissions/558989441/

#define __SANITIZE_ADDRESS__ 0
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("unroll-loops")

class Solution {
public:
    int maxFrequency(vector<int>& v, int k) {
        int l = 0, r = 0, n = v.size();
        long long sum = 0; int ans = 0;

        sort(begin(v), end(v));
        while (r < n) {
            sum += v[r];

            while (1LL* (r-l+1) * v[r] > sum + k) sum -= v[l++];
            ans = max(ans, r-l+1);
            r++;
        }
        return ans;
    }
};